package com.kming.crypto.util;

import org.springframework.core.DefaultParameterNameDiscoverer;

import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.List;

@SuppressWarnings("unused")
public class ReflectionUtils extends org.springframework.util.ReflectionUtils {
    private static final DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();

    /**
     * 查找构造器
     * @param className 类名
     * @param paramNames 构造器参数名
     * @return java.lang.reflect.Constructor 构造器
     * @throws ClassNotFoundException 如果该类未找到则抛出异常
     */
    public static Constructor<?> findConstructor(String className, String[] paramNames) throws ClassNotFoundException{
        Class<?> clazz = Class.forName(className);
        return findConstructor(clazz, paramNames);
    }

    /**
     * 查找构造器
     * @param clazz 类
     * @param paramNames 构造器参数名
     * @return java.lang.reflect.Constructor 构造器
     */
    public static Constructor<?> findConstructor(Class<?> clazz, String[] paramNames) {
        if (paramNames.length == 0){
            return cn.hutool.core.util.ReflectUtil.getConstructor(clazz);
        }
        Constructor<?>[] constructors = cn.hutool.core.util.ReflectUtil.getConstructors(clazz);
        final List<String> paramNameList = Arrays.asList(paramNames);
        for (Constructor<?> ctor : constructors) {
            String[] ctorParamNames = discoverer.getParameterNames(ctor);
            if (ctorParamNames == null || ctorParamNames.length == 0){
                continue;
            }
            if(Arrays.stream(ctorParamNames).allMatch(paramNameList::contains)){
                return ctor;
            }
        }
        return null;
    }
}
